﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using SIPO.Library.DataAccess.Report;
using SIPO.Library.DomainObject.Administration.Catalog;
using SIPO.Library.DataAccess.Administration.Catalog;
using SIPO.Web.Support;
using Microsoft.Reporting.WebForms;
using SIPO.Library.DataAccess.Transaction;


namespace SIPO.Web.lists.Report
{
    public partial class rptPenerimaanlist : BasePage
    {
        rptPenerimaanRepo penerimaanDal = new rptPenerimaanRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        recBillingRepo recBillingDal = new recBillingRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        recDayOffRepo recDayOffDal = new recDayOffRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);

        protected override void OnLoad(EventArgs e)
        {

            if (!IsPostBack)
            {

                recTransactionTypeRepo recTransactionTypeDal = new recTransactionTypeRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
                //populate dropdownlist transactionType
                List<recTransactionType> transTypes = recTransactionTypeDal.GetListOnBilling();

                ddlJenisPungutan.Items.Clear();
                if (transTypes.Count > 0)
                {
                    transTypes.ForEach(delegate(recTransactionType transType)
                    {
                        ddlJenisPungutan.Items.Add(new ListItem(transType.TransTypeCode + "-" + transType.TransTypeName, transType.TransTypeID.ToString()));
                    });
                }
                ddlJenisPungutan.Items.Insert(0, new ListItem("-- semua jenis pungutan --", string.Empty));

            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string sectorID = hfSektorID.Value == "pilih sektor..." || hfSektorID.Value == "" ? string.Empty : pisahkan(hfSektorID.Value);
            string subSectorID = hfSubSektorID.Value == "pilih sub sektor..." || hfSubSektorID.Value == "" ? string.Empty : pisahkan(hfSubSektorID.Value);
            string subSubSectorID = hfSubSubSektorID.Value == "pilih sub sub sektor..." || hfSubSubSektorID.Value == "" ? string.Empty : pisahkan(hfSubSubSektorID.Value);
            string transTypeID = hfTransTypeID.Value;
            string periodeAwal = hfPeriodeAwal.Value == "Periode Awal" || hfPeriodeAwal.Value == "" ? string.Empty : hfPeriodeAwal.Value;
            string periodeAkhir = hfPeriodeAkhir.Value == "Periode Akhir" || hfPeriodeAkhir.Value == "" ? string.Empty : hfPeriodeAkhir.Value;
            string detail = hfDetail.Value;
            string sPeriodeAwal = string.Empty;
            string sPeriodeAkhir = string.Empty;

            string parameter = string.Empty;

            string parameterTerminDueDate = string.Empty;

            DateTime dateCurrent = Convert.ToDateTime(recDayOffDal.GetCurrentDateFromRecParameter().ToString("dd/MM/yyyy"));

            //ambil termin is formula

            DateTime dateTerminIsFormula = new DateTime();
            List<string> listTerminIsFormula = recBillingDal.GetTerminDueDateIsFormula();
            foreach (string terminFormula in listTerminIsFormula)
            {
                dateTerminIsFormula = Convert.ToDateTime(terminFormula + "/" + dateCurrent.ToString("yyyy"));
                dateTerminIsFormula = recDayOffDal.GetDueDate(dateTerminIsFormula.ToString("yyyyMMdd"));
            }

            //end

            //Ambil Termin Due Date

            List<string> listTermin = recBillingDal.GetTerminDueDate();
            foreach (string terminDate in listTermin)
            {
                //DateTime dateCurrent = Convert.ToDateTime(DateTime.Now.ToString("dd/MM/yyyy"));

                DateTime dateTermin = Convert.ToDateTime(terminDate + "/" + dateCurrent.ToString("yyyy"));
                dateTermin = recDayOffDal.GetDueDate(dateTermin.ToString("yyyyMMdd"));

                if (dateCurrent <= dateTermin)
                {
                    parameterTerminDueDate = " AND ( recBilling.DueDate <= CONVERT(DATETIME, '" + dateTermin.ToString("dd/MM/yyyy") + "', 103) OR recBilling.DueDate <= CONVERT(DATETIME, '" + dateTerminIsFormula.ToString("dd/MM/yyyy") + "', 103) )";
                    break;
                }
            }
            //end


            //konversi tanggal
            if (!periodeAwal.Equals(string.Empty))
            {
                sPeriodeAwal = string.Format("{0:yyyyMMdd}", Helper.FormatDate(periodeAwal, Helper.Culture.Indonesian));
            }

            if (!periodeAkhir.Equals(string.Empty))
            {
                sPeriodeAkhir = string.Format("{0:yyyyMMdd}", Helper.FormatDate(periodeAkhir, Helper.Culture.Indonesian));
            }




            if (!sectorID.Equals(string.Empty))
            {
                string param = sectorID;

                if (!subSectorID.Equals(string.Empty))
                {
                    param += "-" + subSectorID;

                    if (!subSubSectorID.Equals(string.Empty))
                    {
                        param += "-" + subSubSectorID;
                    }
                    else
                        param += "-";
                }
                else
                    param += "--";
                parameter += GenerateWhere(param);

                if (!sPeriodeAwal.Equals(string.Empty) && !sPeriodeAkhir.Equals(string.Empty))
                {
                    parameter += " and recBilling.BillingDate between '" + sPeriodeAwal + "' and '" + sPeriodeAkhir + "'";
                }

                if (!transTypeID.Equals(string.Empty))
                {
                    parameter += " and recTransactionType.TransTypeID= '" + transTypeID + "'";
                }
            }
            else
            {
                if (!sPeriodeAwal.Equals(string.Empty) && !sPeriodeAkhir.Equals(string.Empty))
                {
                    parameter += " and recBilling.BillingDate between '" + sPeriodeAwal + "' and '" + sPeriodeAkhir + "'";
                }

                if (!transTypeID.Equals(string.Empty))
                {
                    parameter += " and recTransactionType.TransTypeID= '" + transTypeID + "'";
                }
            }

            string tglPeriodeAwal = penerimaanDal.PeriodeLaporan(periodeAwal);
            string tglPeriodeAkhir = penerimaanDal.PeriodeLaporan(periodeAkhir);
            string parametersRegistrasi = parameter;

            try
            {
                DataTable dt = penerimaanDal.GetPenerimaan(parameter, parameterTerminDueDate, sPeriodeAwal, sPeriodeAkhir,parametersRegistrasi);

                rsViewer.Reset();
                string path = detail == "1" ? "~/reportviewer/Transaction/rptIncomeDetail.rdlc" : "~/reportviewer/Transaction/rptIncome.rdlc";
                rsViewer.LocalReport.ReportPath = Server.MapPath(path);
                ReportDataSource rds = new ReportDataSource();
                rds.Name = "DataSet1";
                rds.Value = dt;

                ReportParameter[] paramReport = new ReportParameter[1];
                paramReport[0] = new ReportParameter("PeriodeLaporan", "Periode Laporan : " + tglPeriodeAwal + " - " + tglPeriodeAkhir);
                rsViewer.LocalReport.SetParameters(paramReport);

                rsViewer.LocalReport.DataSources.Clear();
                rsViewer.LocalReport.DataSources.Add(rds);
                rsViewer.LocalReport.Refresh();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void rsViewer_Drillthrough(object sender, DrillthroughEventArgs e)
        {
            ReportParameterInfoCollection drillTroughValues = e.Report.GetParameters();
            string debtorID = string.Empty;
            string transTypeID = string.Empty;
            string sectorID = hfSektorID.Value == "pilih sektor..." || hfSektorID.Value == "" ? string.Empty : pisahkan(hfSektorID.Value);
            string subSectorID = hfSubSektorID.Value == "pilih sub sektor..." || hfSubSektorID.Value == "" ? string.Empty : pisahkan(hfSubSektorID.Value);
            string subSubSectorID = hfSubSubSektorID.Value == "pilih sub sub sektor..." || hfSubSubSektorID.Value == "" ? string.Empty : pisahkan(hfSubSubSektorID.Value);
            //transTypeID = hfTransTypeID.Value;
            string periodeAwal = hfPeriodeAwal.Value == "Periode Awal" || hfPeriodeAwal.Value == "" ? string.Empty : hfPeriodeAwal.Value;
            string periodeAkhir = hfPeriodeAkhir.Value == "Periode Akhir" || hfPeriodeAkhir.Value == "" ? string.Empty : hfPeriodeAkhir.Value;
            string detail = hfDetail.Value;
            string sPeriodeAwal = string.Empty;
            string sPeriodeAkhir = string.Empty;

            string parameter = string.Empty;

            string parameterTerminDueDate = string.Empty;

            DateTime dateCurrent = Convert.ToDateTime(recDayOffDal.GetCurrentDateFromRecParameter().ToString("dd/MM/yyyy"));

            //ambil termin is formula

            DateTime dateTerminIsFormula = new DateTime();
            List<string> listTerminIsFormula = recBillingDal.GetTerminDueDateIsFormula();
            foreach (string terminFormula in listTerminIsFormula)
            {
                dateTerminIsFormula = Convert.ToDateTime(terminFormula + "/" + dateCurrent.ToString("yyyy"));
                dateTerminIsFormula = recDayOffDal.GetDueDate(dateTerminIsFormula.ToString("yyyyMMdd"));
            }

            //end

            //Ambil Termin Due Date

            List<string> listTermin = recBillingDal.GetTerminDueDate();
            foreach (string terminDate in listTermin)
            {
                //DateTime dateCurrent = Convert.ToDateTime(DateTime.Now.ToString("dd/MM/yyyy"));

                DateTime dateTermin = Convert.ToDateTime(terminDate + "/" + dateCurrent.ToString("yyyy"));
                dateTermin = recDayOffDal.GetDueDate(dateTermin.ToString("yyyyMMdd"));

                if (dateCurrent <= dateTermin)
                {
                    parameterTerminDueDate = " AND ( recBilling.DueDate <= CONVERT(DATETIME, '" + dateTermin.ToString("dd/MM/yyyy") + "', 103) OR recBilling.DueDate <= CONVERT(DATETIME, '" + dateTerminIsFormula.ToString("dd/MM/yyyy") + "', 103) )";
                    break;
                }
            }
            //end


            //konversi tanggal
            if (!periodeAwal.Equals(string.Empty))
            {
                sPeriodeAwal = string.Format("{0:yyyyMMdd}", Helper.FormatDate(periodeAwal, Helper.Culture.Indonesian));
            }

            if (!periodeAkhir.Equals(string.Empty))
            {
                sPeriodeAkhir = string.Format("{0:yyyyMMdd}", Helper.FormatDate(periodeAkhir, Helper.Culture.Indonesian));
            }




            if (!sectorID.Equals(string.Empty))
            {
                string param = sectorID;

                if (!subSectorID.Equals(string.Empty))
                {
                    param += "-" + subSectorID;

                    if (!subSubSectorID.Equals(string.Empty))
                    {
                        param += "-" + subSubSectorID;
                    }
                    else
                        param += "-";
                }
                else
                    param += "--";
                parameter += GenerateWhere(param);

                if (!sPeriodeAwal.Equals(string.Empty) && !sPeriodeAkhir.Equals(string.Empty))
                {
                    parameter += " and recBilling.BillingDate between '" + sPeriodeAwal + "' and '" + sPeriodeAkhir + "'";
                }

                //if (!transTypeID.Equals(string.Empty))
                //{
                //    parameter += " and recTransactionType.TransTypeID= '" + transTypeID + "'";
                //}
            }
            else
            {
                if (!sPeriodeAwal.Equals(string.Empty) && !sPeriodeAkhir.Equals(string.Empty))
                {
                    parameter += " and recBilling.BillingDate between '" + sPeriodeAwal + "' and '" + sPeriodeAkhir + "'";
                }

                //if (!transTypeID.Equals(string.Empty))
                //{
                //    parameter += " and recTransactionType.TransTypeID= '" + transTypeID + "'";
                //}
            }

            string parametersRegistrasi = parameter;
            foreach (ReportParameterInfo d in drillTroughValues)
            {
                if (d.Name.ToLower() == "debtorid")
                {
                    debtorID = !string.IsNullOrEmpty(d.Values[0]) ? d.Values[0].ToString().Trim() : string.Empty;
                    parameter += " and recDebtor.DebtorID = '" + debtorID + "'";
                }

                if (d.Name.ToLower() == "transtypeid")
                {
                    transTypeID = !string.IsNullOrEmpty(d.Values[0]) ? d.Values[0].ToString().Trim() : string.Empty;
                    parameter += " and recTransactionType.TransTypeID = '" + transTypeID + "'";

                    parametersRegistrasi += " and recTransactionType.TransTypeID = '" + transTypeID + "'";
                }
            }



            LocalReport localreport = (LocalReport)e.Report;
            ReportDataSource rds = new ReportDataSource();

            DataTable dt = null;

            localreport.ReportPath = Server.MapPath("~/reportviewer/Transaction/rptIncomeDetailView.rdlc");
            recTransactionTypeRepo recTransactionTypeDal = new recTransactionTypeRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
            recTransactionType objTransType = recTransactionTypeDal.GetById(short.Parse(transTypeID));
            int transTypeCode = objTransType == null ? 0 : objTransType.TransTypeCode;

            dt = penerimaanDal.GetPenerimaanDetail(parameter, parameterTerminDueDate, sPeriodeAwal, sPeriodeAkhir, parametersRegistrasi, Convert.ToInt32(debtorID), transTypeCode);
            rds.Name = "DataSet1";
            rds.Value = dt;

            string tglPeriodeAwal = penerimaanDal.PeriodeLaporan(periodeAwal);
            string tglPeriodeAkhir = penerimaanDal.PeriodeLaporan(periodeAkhir);

            ReportParameter[] paramReport = new ReportParameter[3];
            paramReport[0] = new ReportParameter("debtorid", "debtorid");
            paramReport[1] = new ReportParameter("transtypeid", "transtypeid");
            paramReport[2] = new ReportParameter("PeriodeLaporan", "Periode Laporan : " + tglPeriodeAwal + " - " + tglPeriodeAkhir);
            localreport.SetParameters(paramReport);


            localreport.DataSources.Clear();
            localreport.DataSources.Add(rds);
            localreport.Refresh();

        }

        public string pisahkan(string control)
        {
            string list = control;
            string[] temp;
            //string [] temp1;
            string gabung = string.Empty;
            temp = list.Split(',');
            if (temp.Length > 0)
            {
                for (int i = 0; i < temp.Length - 1; i++)
                {
                    if (i == 0)
                        gabung = temp.ElementAt(i).Split('-').FirstOrDefault();
                    else
                        gabung += "," + temp.ElementAt(i).Split('-').FirstOrDefault();
                }
            }

            return gabung;
        }

        public string GenerateWhere(string param) //generate where sector, subsector, subsubsector
        {

            string[] Sektor = param.Split('-');
            string Sektors = Sektor.ElementAt(0);

            string SektorSubSektors = Sektor.ElementAt(1);

            string SektorSubSubSektors = Sektor.ElementAt(2);

            string[] ArrSektor = Sektors.Split(',');

            string[] ArrSubSektor = SektorSubSektors.Split(',');

            string[] ArrSubSubSektor = SektorSubSubSektors.Split(',');

            string parameters = string.Empty;
            bool status = false;
            for (int i = 0; i < ArrSektor.Length; i++)
            {
                for (int j = 0; j < ArrSubSektor.Length; j++)
                {
                    if (ArrSubSektor.ElementAt(j).ToString().Trim().Split('.').FirstOrDefault() == ArrSektor.ElementAt(i).Trim())
                    {
                        if (parameters == string.Empty)
                            parameters += " where ((recSector.SectorCode = " + ArrSektor.ElementAt(i) + " and recSubSector.SubSectorCode=" + ArrSubSektor.ElementAt(j).ToString().Trim().Substring(2, 1);
                        else
                            parameters += " or (recSector.SectorCode = " + ArrSektor.ElementAt(i) + " and recSubSector.SubSectorCode=" + ArrSubSektor.ElementAt(j).ToString().Trim().Substring(2, 1);
                        status = true;
                        bool stats = false;
                        for (int k = 0; k < ArrSubSubSektor.Length; k++)
                        {
                            if (ArrSubSubSektor.ElementAt(k).ToString().Trim() != "")
                            {
                                if (ArrSubSubSektor.ElementAt(k).ToString().Trim().Split('.').ElementAt(0) == ArrSektor.ElementAt(i).Trim() && ArrSubSubSektor.ElementAt(k).ToString().Trim().Split('.').ElementAt(1) == ArrSubSektor.ElementAt(j).Trim().Split('.').ElementAt(1) && stats==false)
                                {

                                    parameters += " and recSubSubSector.SubSubSectorCode = " + ArrSubSubSektor.ElementAt(k).ToString().Trim().Split('.').ElementAt(2) + ")";
                                    
                                  
                                    stats = true;
                                   // break;
                                }
                                else if(ArrSubSubSektor.ElementAt(k).ToString().Trim().Split('.').ElementAt(0) == ArrSektor.ElementAt(i).Trim() && ArrSubSubSektor.ElementAt(k).ToString().Trim().Split('.').ElementAt(1) == ArrSubSektor.ElementAt(j).Trim().Split('.').ElementAt(1) && stats==true)
                                    parameters += " or (recSector.SectorCode = " + ArrSektor.ElementAt(i) + " and recSubSector.SubSectorCode=" + ArrSubSektor.ElementAt(j).ToString().Trim().Substring(2, 1) +" and recSubSubSector.SubSubSectorCode = " + ArrSubSubSektor.ElementAt(k).ToString().Trim().Split('.').ElementAt(2) + ")";
                                    
                            }

                        }
                        if (stats == false)
                            parameters += ")";

                    }

                }
                if (status == false)
                {

                    if (parameters != string.Empty)
                    {
                        bool stats = false;
                        for (int k = 0; k < ArrSubSubSektor.Length; k++)
                        {
                            if (ArrSubSubSektor.ElementAt(k).ToString().Trim() != "")
                            {
                                if (ArrSubSubSektor.ElementAt(k).ToString().Trim().Split('.').ElementAt(0) == ArrSektor.ElementAt(i).Trim())
                                {
                                    stats = true;

                                    parameters += " or (recSector.SectorCode=" + ArrSektor.ElementAt(i) + " and recSubSector.SubSectorCode=" + ArrSubSubSektor.ElementAt(k).Trim().Split('.').ElementAt(1) + " and recSubSubSector.SubSubSectorCode=" + ArrSubSubSektor.ElementAt(k).ToString().Trim().Split('.').ElementAt(2) + ")";

                                }
                            }
                        }
                        if (stats == false)
                            parameters += " or recSector.SectorCode=" + ArrSektor.ElementAt(i);
                    }
                    else
                    {
                        bool stats = false;
                        for (int k = 0; k < ArrSubSubSektor.Length; k++)
                        {
                            if (ArrSubSubSektor.ElementAt(k).ToString().Trim() != "")
                            {
                                if (ArrSubSubSektor.ElementAt(k).ToString().Trim().Split('.').ElementAt(0) == ArrSektor.ElementAt(i).Trim())
                                {
                                    stats = true;

                                    parameters += " where ((recSector.SectorCode=" + ArrSektor.ElementAt(i) + " and recSubSector.SubSectorCode=" + ArrSubSubSektor.ElementAt(k).Trim().Split('.').ElementAt(1) + " and recSubSubSector.SubSubSectorCode=" + ArrSubSubSektor.ElementAt(k).ToString().Trim().Split('.').ElementAt(2) + ")";

                                }
                            }
                        }
                        if (stats == false)
                            parameters += " where (recSector.SectorCode=" + ArrSektor.ElementAt(i);
                    }

                }
                else
                    status = false;
            }
            return parameters + ")";
        }

    }
}